﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using System.Data;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxUploadControl;
using System.IO;


namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 广告管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class AdController : AdminBaseController
    {   
        //
        // GET: /Admin/Ad/
        /// <summary>
        /// 广告管理首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_Ad", Order = 1)]
        [LogPageActionFilter("广告管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }



        /// <summary>
        ///  编码列表页
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult AdList() 
        {

            int pageIndex = 1;
            List<Model.Ad> adList = GetAdList(pageIndex);

            return View(adList);

        }

        /// <summary>
        /// 编码树相关调用方法 主要用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult AdListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string adNo = Request.Params["adNo"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.Ad> adList = GetAdList(pageIndex, pageCount, pageRowSize);


            return PartialView("AdListPartial", adList);
        }


        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示大小</param>
        /// <param name="pageRowSize">每页显示页数</param>
        /// <returns>广告集合</returns>
        private List<Model.Ad> GetAdList(int pageIndex, int pageCount = 0, int pageRowSize = 0)
        {
            BLL.Ad adBll = new BLL.Ad();
           
            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("t_ad", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, "", "FAdcd", 0, out total);

            List<Model.Ad> adAllList = new List<Model.Ad>();
            List<Model.Ad> adList = adBll.DataTableToListAd(ds.Tables[0]);
            
            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                adAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (adList.Count > i)
                {
                    adAllList[((pageIndex - 1) * pageRowSize) + i] = adList[i];
                }
            }

            return adAllList;
        }

        /// <summary>
        /// 获取广告具体数据
        /// </summary>
        /// <param name="adNo">广告编号</param>
        /// <returns>视图</returns>
        public ActionResult AdContent(string adNo) 
        {
            BLL.Ad adBll = new BLL.Ad();
            Model.Ad adModel = new Model.Ad();

            string strEntityNo = GlobalConstant.ENTITYNO;
            if (adBll.GetQPCount(strEntityNo) > 0)
            {
                ViewData["QP"] = "1";           
            }
            if (adBll.GetRightDlCount(strEntityNo) > 0) {
                ViewData["right"] = "1";
            }
            if (adBll.GetLeftDlCount(strEntityNo) > 0)
            {
                ViewData["left"] = "1";
            }

            bool blad = true;
            bool blac = true;
            if (string.IsNullOrEmpty(adNo))
            {                
                adModel.FIsUse = 1;
                adModel.FDataType = "U";
                adModel.FAdProp = "1";
                adModel.FAdWidth = 0;
                adModel.FAdWidth = 0;
                blad = true;
                blac = false;
                ViewData["ImgYWidth"] = "";
                ViewData["ImgYHeight"] = "";
                ViewData["type"] = "ADD";
            }
            else
            {
                blad = false;
                blac = false;
                adNo = Fetch.estimateString(adNo, CheckGetEnum.Safety);               
                adModel = adBll.GetModel(GlobalConstant.ENTITYNO, adNo);
                if (adModel.FAdUrl == "javascript:;")
                {
                    adModel.FAdUrl = "";
                }
                else {
                    adModel.FAdUrl = adModel.FAdUrl;
                }
                adModel.FAdContent = adModel.FAdContent;
                adModel.FSvrFileName = adModel.FSvrFileName;
                ViewData["adProp"] = adModel.FAdProp;
                ViewData["ImgYWidth"] = adModel.FAdWidth;
                ViewData["ImgYHeight"] = adModel.FAdHeight;
                ViewData["old"] = adModel.FOldFileName;
                ViewData["svr"] = adModel.FSvrFileName;
                ViewData["type"] = "Edit";
                if (null == adModel)
                {
                    adModel = new Model.Ad();
                    adModel.FIsUse = 1;
                    blad = true;
                    blac = true;
                }
                else {
                
                
                }

             }

            ViewData["blad"] = blad;
            ViewData["blac"] = blac;

            return View(adModel);
        }

         /// <summary>
        /// 数据增加修改保存
        /// </summary>
        /// <param name="adModel">广告model</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.Ad adModel)
        {

            BLL.Ad adBll = new BLL.Ad();
            string hidAdNo = Fetch.Post("hidAdNo");
            adModel = adBll.GetModel(GlobalConstant.ENTITYNO, hidAdNo);
            if (adModel == null) {
                adModel = new Model.Ad();
            }    


            string type = "add";
            if (hidAdNo != string.Empty)
            {
                type = "edit";
            }

            ActionResult asctionResult = null;
           
            UploadedFile[] fileList = UploadControlExtension.GetUploadedFiles("picUpload");
            if (null != fileList && fileList.Length > 0)
            {
                UploadedFile upload = fileList[0];
                if (upload.ContentLength > 0)
                {
                    string backname = upload.FileName.Substring(upload.FileName.LastIndexOf('.') + 1);
                    string entityNo = GlobalConstant.ENTITYNO;
                    string dest_dir = "Publish/AD/" + entityNo + "/upload/";
                    string svrFileName = Path.GetFileNameWithoutExtension(upload.FileName);//上传的文件名
                    string uploadoffiepath = Server.MapPath(Url.Content("~") + dest_dir);//上传文件的路径
                    if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                    {
                        Directory.CreateDirectory(uploadoffiepath);
                    }
                    upload.SaveAs(uploadoffiepath + svrFileName + "." + backname);

                    adModel.FAdContent = upload.FileBytes;
                    adModel.FSvrFileName = Url.Content("~") + dest_dir + Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                    adModel.FAdType = upload.ContentType;
                    adModel.FOldFileName = Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                }
            }

            try
            {
                if (type == "add")
                {
                    adModel.FAdcd = Fetch.Post("FAdcd");
                    adModel.FEntityNo = GlobalConstant.ENTITYNO;
                    adModel.FAdName = Fetch.Post("FAdName");
                    adModel.FDataType = "U";
                    adModel.FAdUrl = Fetch.Post("FAdUrl") == "" ? "javaccript:;" : Fetch.Post("FAdUrl");
                    adModel.FIsUse = DropDownEditExtension.GetValue<decimal>("FIsUse");
                    adModel.FAdHeight = Fetch.Post("FAdHeight").Trim() == "" ? 0 : Int32.Parse(Fetch.Post("FAdHeight"));
                    adModel.FAdWidth = Fetch.Post("FAdWidth").Trim() == "" ? 0 : Int32.Parse(Fetch.Post("FAdWidth"));
                    adModel.FAdProp = ComboBoxExtension.GetValue<string>("FAdProp");

                    adBll.Add(adModel);
              
                }
                else if (type == "edit")
                {
                    adModel.FAdcd = Fetch.Post("FAdcd");
                    adModel.FEntityNo = GlobalConstant.ENTITYNO;
                    adModel.FAdName = Fetch.Post("FAdName");
                    adModel.FDataType = "U";
                    adModel.FAdUrl = Fetch.Post("FAdUrl") == "" ? "javaccript:;" : Fetch.Post("FAdUrl");
                    adModel.FIsUse = DropDownEditExtension.GetValue<decimal>("FIsUse");
                    adModel.FAdHeight = Fetch.Post("FAdHeight").Trim() == "" ? 0 : Int32.Parse(Fetch.Post("FAdHeight"));
                    adModel.FAdWidth = Fetch.Post("FAdWidth").Trim() == "" ? 0 : Int32.Parse(Fetch.Post("FAdWidth"));
                    adModel.FAdProp = ComboBoxExtension.GetValue<string>("FAdProp");

                    adBll.Update(adModel);
   
                }

               


                ViewData["blac"] = true;
                ViewData["blad"] = true;
                ViewData["message"] = "操作成功";
                ViewData["IsClose"] = "Y";
                return View("AdContent", adModel);
               
            }
            catch (Exception)
            {
                ViewData["blac"] = true;
                ViewData["blad"] = true;
                ViewData["message"] = "保存失败";
                ViewData["IsClose"] = "N";
                asctionResult = View("AdContent", adModel);

            }

            return asctionResult;
        }


        /// <summary>
        /// 批量删除广告数据
        /// </summary>
        /// <param name="adNos">广告编号</param>
        /// <returns>ok删除成功，error删除失败</returns>
        [HttpPost]
        public string DeleteManyAd(string adNos)
        {
            string str = string.Empty;
            string strEntityNo = GlobalConstant.ENTITYNO;
            
            string[] adArray = adNos.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);
            List<string> imgPathList = GetManyPathList(adArray, strEntityNo);
            BLL.Ad adBll = new BLL.Ad();

            try
            {
                DeleteImg(imgPathList);//删除保存在硬盘的图片
                adBll.DelManyAd(adArray, GlobalConstant.ENTITYNO);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        }

        /// <summary>
        /// 判断编号是否已存在
        /// </summary>
        /// <param name="adNo">广告编号</param>
        /// <returns>Y表示存在，N表示不存在</returns>
        [HttpPost]
        public string ExistsAd(string fAdcd)
        {
            ViewData["blac"] = true;
            string str = string.Empty;
            BLL.Ad adBll = new BLL.Ad();
            if (adBll.Exists(fAdcd, Common.GlobalConstant.ENTITYNO))
            {
                str = "Y";
            }
            else
            {
                str = "N";
            }

            
            return str;
        }


        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="adNo">广告编号</param>
        /// <returns>ok，删除成功，error删除失败</returns>
        [HttpPost]
        public string DelAd(string adNo)
        {
            string strEntityNo = GlobalConstant.ENTITYNO;
            List<string> imgPathList = GetPathList(adNo, strEntityNo);//获取保存在硬盘中的图片路径list
            adNo = Fetch.estimateString(adNo, CheckGetEnum.Safety);
            string str = string.Empty;
            BLL.Ad adBll = new BLL.Ad();
            try
            {
                DeleteImg(imgPathList);//删除保存在硬盘的图片
                adBll.DelAd(adNo, GlobalConstant.ENTITYNO);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }

        /// <summary>
        /// 获取保存在硬盘中的图片路径 批量删除
        /// </summary>
        /// <param name="strAdCds">广告编号</param>
        /// <param name="strEntityNo">公司编号</param>
        /// <returns>图片路径</returns>

        public List<string> GetManyPathList(string[] strAdCds, string strEntityNo)
        {
            BLL.Ad adBll = new BLL.Ad();
            List<string> strList = adBll.GetManySrvName(strAdCds, strEntityNo);
            return strList;
        }

        /// <summary>
        /// 获取保存在硬盘中的图片路径
        /// </summary>
        /// <param name="strAdCds">广告编号</param>
        /// <param name="strEntityNo">公司编号</param>
        /// <returns>图片路径</returns>

        public List<string> GetPathList(string strAdCds, string strEntityNo)
        {
            BLL.Ad adBll = new BLL.Ad();
            List<string> strList = adBll.GetSrvName(strAdCds, strEntityNo);
            return strList;
        }

        /// <summary>
        /// 删除保存在硬盘的图片
        /// </summary>
        /// <param name="strList">图片路径list</param>
        public void DeleteImg(List<string> strList)
        {
            foreach (string strPath in strList)
            {
                GenerateUtil.DeleteFile(Url.Content("~") + strPath);
            }
        }

    }
}
